package com.sky.aspect;

import com.sky.anno.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自定义公共字段自动填充切面类
 */

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Before("@annotation(com.sky.anno.AutoFill)")
    public void before(JoinPoint joinPoint) {
        log.info("公共字段自动填充");
        /**
         * 1.获取目标方法注解，并获取注解里的枚举值
         * 2.判断属性值：如果是update，更新两个字段，create更新四个字段
         * 3.获取目标方法参数，操作
         */

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        OperationType value = annotation.value();

        Object[] o =joinPoint.getArgs();
        if(o==null|| o.length==0){
            return;
        }
        Object entity=o[0];
        //开始反射
        try {
            if(value == OperationType.UPDATE){
               Method setUpdateUser=entity.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                setUpdateUser.invoke(entity, BaseContext.getCurrentId());
               Method setUpdateTime=entity.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
               setUpdateTime.invoke(entity,LocalDateTime.now());
            }
            else if(value == OperationType.INSERT){
                Method setUpdateUser=entity.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                setUpdateUser.invoke(entity, BaseContext.getCurrentId());
                Method setUpdateTime=entity.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                setUpdateTime.invoke(entity,LocalDateTime.now());
                Method setCreateUser=entity.getClass().getMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
                setCreateUser.invoke(entity, BaseContext.getCurrentId());
                Method setCreateTime=entity.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
                setCreateTime.invoke(entity,LocalDateTime.now());


            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
